package com.xm.transfer.utils;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ClassUtils {

    private static final char PKG_SEPARATOR = '.';

    private static final char DIR_SEPARATOR = '/';

    private static final String CLASS_FILE_SUFFIX = ".class";

    public static List<Class<?>> finds(String pack) {
        String scanPath = pack.replace(PKG_SEPARATOR, DIR_SEPARATOR);
        URL resource = Thread.currentThread().getContextClassLoader().getResource(scanPath);
        if (null == resource) {
            throw new RuntimeException("包异常，检查");
        }
        File file = new File(resource.getFile());
        List<Class<?>> classes = new ArrayList<>();
        for (File tmpFile : file.listFiles()) {
            classes.addAll(finds(tmpFile, scanPath));
        }
        return classes;
    }

    private static List<Class<?>> finds(File file, String scanPath) {
        List<Class<?>> classes = new ArrayList<>();
        String resource = scanPath + DIR_SEPARATOR + file.getName();
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                classes.addAll(finds(child, resource));
            }
        } else if (resource.endsWith(CLASS_FILE_SUFFIX)) {
            int endIndex = resource.length() - CLASS_FILE_SUFFIX.length();
            String className = resource.substring(0, endIndex);
            try {
                classes.add(Class.forName(className.replace(DIR_SEPARATOR, PKG_SEPARATOR)));
            } catch (ClassNotFoundException ignore) {
                ignore.printStackTrace();
            }
        }
        return classes;
    }

    public static void main(String[] args) {
        List<Class<?>> finds = ClassUtils.finds("com.xm.transfer");
        for (int i = 0; i < finds.size(); i++) {
            System.out.println(finds.get(i).getSimpleName());
        }
    }
}
